﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atomic.Db;
using Atomic.User.Entities;
using NHibernate;
using NHibernate.Linq;
using Atomic.Common;
using System.Data;

namespace Atomic.User.DAL
{
    /// <summary>
    /// SQLServer2000+
    /// </summary>
    public class UserBaseDAL : BaseDAL<UserBaseEntity>
    {
        public UserBaseDAL()
            : base() { }
        public UserBaseDAL(ISession session)
            : base(session) { }

        /// <summary>
        /// 添加用户扩展信息到用户对应的数据表中
        /// </summary>
        /// <param name="list">添加的信息列表</param>
        /// <param name="userTypeID">用户类型ID</param>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public virtual object AddExtendData(List<KeyValuePair<string, object>> list, int userTypeID, int id)
        {
            string sql = "Insert Into UserExtend{0}({1}) Values({2})";
            List<string> fields = new List<string>();
            List<object> values = new List<object>();

            //加载字段和值
            fields.Add("ID");   //主键（对应基础表中的用户ID）
            values.Add(id);
            foreach (KeyValuePair<string, object> item in list)
            {
                fields.Add(item.Key);
                values.Add(item.Value);
            }

            sql = string.Format(sql,
                userTypeID,
                fields.ToSplitString(","),
                values.ToSQLInsertValues());
            return session.CreateSQLQuery(sql).ExecuteUpdate();
        }

        /// <summary>
        /// 更新扩展表信息
        /// </summary>
        /// <param name="list">更新字段列表</param>
        /// <param name="userTypeID">用户类型ID</param>
        /// <param name="id">用户ID</param>
        public virtual void UpdateExtendData(List<KeyValuePair<string, object>> list, int userTypeID, int id)
        {
            string sql = "Update UserExtend{0} Set {1} Where ID={2}";
            if (list != null
                && list.Count > 0)
            {
                sql = string.Format(sql,
                    userTypeID,
                    list.ToSQLUpdateValues(),
                    id);
                session.CreateSQLQuery(sql).ExecuteUpdate();    //更新
            }
        }

        /// <summary>
        /// 删除用户扩展信息
        /// </summary>
        /// <param name="userTypeID">用户类型</param>
        /// <param name="id">用户ID</param>
        public virtual void RemoveExtendData(int userTypeID, int id)
        {
            string sql = "Delete From UserExtend{0} Where ID={1}";
            sql = string.Format(sql, userTypeID, id);
            session.CreateSQLQuery(sql).ExecuteUpdate();
        }

        /// <summary>
        /// 从指定用户的用户类型的扩展信息表中获取用户对应的扩展信息
        /// </summary>
        /// <param name="userTypeID">用户类型</param>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public virtual List<KeyValuePair<string, object>> GetExtendData(int userTypeID, int id)
        {
            List<KeyValuePair<string, object>> extendData = new List<KeyValuePair<string, object>>();   //初始化扩展属性
            //该类型的扩展字段
            List<UserExtendFieldEntity> extendFields = session.Query<UserExtendFieldEntity>()
                .Where(m => m.UserTypeID.Equals(userTypeID))
                .ToList();
            //关联扩展表信息
            ISQLQuery query = session.CreateSQLQuery(string.Format("Select * From UserExtend{0} Where ID={1}", userTypeID, id));
            query.AddScalar("ID", NHibernateUtil.Int32);    //主键
            extendData.Add(new KeyValuePair<string, object>("ID", null));
            foreach (UserExtendFieldEntity item in extendFields)
            {
                query.AddScalar(item.Name, NHibernateUtil.String);
                extendData.Add(new KeyValuePair<string, object>(item.Name, null));
            }

            //扩展信息结果赋值扩展数据属性中
            object extendEntity = query.List<object>().FirstOrDefault();
            if (extendEntity != null)
            {
                object[] datas = extendEntity.As<object[]>();
                for (int i = 0; i < datas.Length; i++)
                {
                    extendData[i] = new KeyValuePair<string, object>(extendData[i].Key, datas[i]);
                }
            }
            return extendData;
        }

        /// <summary>
        /// 查询用户详细信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户信息</returns>
        public override UserBaseEntity Get(object id)
        {
            UserBaseEntity entity = base.Get(id);
            if (entity == null)
            {
                throw new Exception("找不到指定ID用户基础信息：" + id);
            }
            entity.ExtendData = this.GetExtendData(entity.TypeID, entity.ID);   //获取用户扩展信息
            return entity;
        }

        /// <summary>
        /// 查询用户详细信息
        /// </summary>
        /// <param name="id">查询过滤条件</param>
        /// <returns>用户信息</returns>
        public override UserBaseEntity Get(System.Linq.Expressions.Expression<Func<UserBaseEntity, bool>> predicate)
        {
            UserBaseEntity entity = base.Get(predicate);
            if (entity == null)
            {
                throw new Exception("找不到指定满足条件的用户基础信息");
            }
            entity.ExtendData = this.GetExtendData(entity.TypeID, entity.ID);   //获取用户扩展信息
            return entity;
        }
    }
}
